extends IEventBehavior


class_name HitScreen
"""
击中边界时,从屏幕另一侧出现
"""


enum ScreenMode {
    CROSS,
    REFECT,
}


## 触发的模式
@export var mode: ScreenMode = ScreenMode.CROSS


func support() -> Array:
    return [CharacterUnit.Event.ON_HIT_OUT_OF_SCREEN]

## 处理武器事件,返回是否取消销毁子弹
func do_event(character: CharacterComponent, v: EffectValue, e: CharacterEvent) -> void:
    if mode == ScreenMode.CROSS:
        cross_screen(character, v, e)
    elif mode == ScreenMode.REFECT:
        refect_screen(character, v, e)

func cross_screen(character: CharacterComponent, v: EffectValue, e: CharacterEvent) -> void:
    var p: Projectile = e.meta.projectile
    var pos: Vector2 = p.global_position
    var rect: Rect2 = p.get_viewport_rect()
    var is_move_x: bool = true
    var is_move_y: bool = true
    if pos.x <= rect.position.x:
        p.global_position.x = rect.end.x
    elif pos.x >= rect.end.x:
        p.global_position.x = rect.position.x
    else:
        is_move_x = false
    if pos.y <= rect.position.y:
        p.global_position.y = rect.end.y
    elif pos.y >= rect.end.y:
        p.global_position.y = rect.position.y
    else:
        is_move_y = false
    if is_move_x or is_move_y:
        v.value -= 1
        e.cancel()

func refect_screen(character: CharacterComponent, v: EffectValue, e: CharacterEvent) -> void:
    var p: Projectile = e.meta.projectile
    var outside_p: Vector2 = p.global_position + e.meta.direction * 10
    var d: Vector2 = e.meta.direction.rotated(PI)
    var data: Dictionary = ShapeDraw.get_first_rect_collision_normal(p.get_viewport_rect(), outside_p, d)
    if data.is_empty():
        return
    var move: MoveComponent = p.element.subassembly("Move")
    if move:
        move.turn(move.direction.bounce(data.normal))
        v.value -= 1
        e.cancel()
